package com.ruoyi.course.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.course.vo.ExamClassCourseVo;
import com.ruoyi.course.vo.ExamClassUserVo;
import com.ruoyi.course.vo.ExamClassVo;
import com.ruoyi.course.vo.ExamClassDetailVo;
import com.ruoyi.course.domain.ClassUserTemplate;
import com.ruoyi.course.service.IExamClassService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletResponse;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 考试班次Controller
 *
 * @author Tellsea
 * @date 2025-09-26
 */
@Api(tags = "考试班次Controller")
@RestController
@RequestMapping("/course/class")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class ExamClassController extends BaseController {

    private final IExamClassService examClassService;

    @ApiOperation("查询考试班次列表")
    @PreAuthorize("@ss.hasPermi('course:class:list')")
    @GetMapping("/list")
    public TableDataInfo<ExamClassVo> list(ExamClassVo entity) {
        return examClassService.queryList(entity);
    }

    @ApiOperation("查询考试班次所有列表")
    @GetMapping("/listAll")
    public AjaxResult listAll(ExamClassVo entity) {
        return AjaxResult.success("查询成功", examClassService.queryAll(entity));
    }

    @ApiOperation("导出考试班次列表")
    @PreAuthorize("@ss.hasPermi('course:class:export')")
    @Log(title = "考试班次", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ExamClassVo entity) {
        List<ExamClassVo> list = examClassService.queryAll(entity);
        ExcelUtil<ExamClassVo> util = new ExcelUtil<>(ExamClassVo.class);
        util.exportExcel(response, list, "考试班次数据");
    }

    @ApiOperation("获取考试班次详细信息")
    @PreAuthorize("@ss.hasPermi('course:class:query')")
    @GetMapping(value = "/getInfo/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success("查询成功", examClassService.queryById(id));
    }

    @ApiOperation("获取考试班次详情（包含关联课程）")
    @PreAuthorize("@ss.hasPermi('course:class:query')")
    @GetMapping(value = "/getDetail/{id}")
    public AjaxResult getDetail(@PathVariable("id") Long id) {
        ExamClassDetailVo result = examClassService.queryDetailById(id);
        if (result == null) {
            return AjaxResult.error("班次不存在");
        }
        return AjaxResult.success("查询成功", result);
    }

    @ApiOperation("新增考试班次")
    @PreAuthorize("@ss.hasPermi('course:class:add')")
    @Log(title = "考试班次", businessType = BusinessType.INSERT)
    @PostMapping("add")
    public AjaxResult add(@RequestBody ExamClassVo entity) {
        return toAjax(examClassService.save(entity));
    }

    @ApiOperation("修改考试班次")
    @PreAuthorize("@ss.hasPermi('course:class:edit')")
    @Log(title = "考试班次", businessType = BusinessType.UPDATE)
    @PostMapping("edit")
    public AjaxResult edit(@RequestBody ExamClassVo entity) {
        return toAjax(examClassService.updateById(entity));
    }

    @ApiOperation("删除考试班次")
    @PreAuthorize("@ss.hasPermi('course:class:remove')")
    @Log(title = "考试班次", businessType = BusinessType.DELETE)
	@GetMapping("/remove/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(examClassService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    @ApiOperation("下载课程班次人员列表")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<ClassUserTemplate> util = new ExcelUtil<ClassUserTemplate>(ClassUserTemplate.class);
        util.importTemplateExcel(response, "课程班次人员模板");
    }

    @ApiOperation("导入课程班次学员列表")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, Long classId) throws Exception {
        ExcelUtil<ClassUserTemplate> util = new ExcelUtil<ClassUserTemplate>(ClassUserTemplate.class);
        List<ClassUserTemplate> studnetList = util.importExcel(file.getInputStream());
        Long result = examClassService.importData(studnetList, classId);
        return AjaxResult.success(result);
    }

    @ApiOperation("新增班次学员")
    @PostMapping("/addClassStudent")
    public AjaxResult addClassStudent(@RequestBody  ExamClassUserVo entity) {
        List<ClassUserTemplate> studnetList = new ArrayList<>();
        ClassUserTemplate studnet = new ClassUserTemplate();
        studnet.setUserName(entity.getUserName());
        studnet.setPhone(entity.getPhone());
        studnet.setGender(entity.getGender());
        studnet.setIdCardNumber(entity.getIdCardNumber());
        studnetList.add(studnet);
        Long result = examClassService.importData(studnetList, entity.getClassId());
        return AjaxResult.success(result);
    }

    @ApiOperation("查询班次学员分页列表")
    @GetMapping("/students/{classId}")
    public TableDataInfo<ExamClassUserVo> getClassStudents(@PathVariable("classId") Long classId, ExamClassUserVo entity) {
        entity.setClassId(classId);
        return examClassService.queryClassStudentList(entity);
    }

    @ApiOperation("移除班次学员")
    @Log(title = "移除班次学员", businessType = BusinessType.DELETE)
    @DeleteMapping("/removeStudent/{classId}/{userId}")
    public AjaxResult removeClassStudent(@PathVariable("classId") Long classId, @PathVariable("userId") Long userId) {
        return toAjax(examClassService.removeClassStudent(classId, userId));
    }

    @ApiOperation("查询班次课程列表")
    @GetMapping("/courses/{classId}")
    public TableDataInfo<ExamClassCourseVo> getClassCourses(@PathVariable("classId") Long classId, ExamClassCourseVo entity) {
        entity.setClassId(classId);
        return examClassService.queryClassCourseList(entity);
    }

    @ApiOperation("新增班次课程关系")
    @Log(title = "新增班次课程关系", businessType = BusinessType.INSERT)
    @PostMapping("/addCourse/{classId}")
    public AjaxResult addClassCourse(@PathVariable("classId") Long classId, @RequestBody List<Long> courseIds) {
        if (courseIds == null || courseIds.isEmpty()) {
            return AjaxResult.error("课程ID列表不能为空");
        }
        int successCount = examClassService.addClassCourses(classId, courseIds);
        return AjaxResult.success("成功添加 " + successCount + " 个课程关系", successCount);
    }

    @ApiOperation("移除班次课程关系")
    @Log(title = "移除班次课程关系", businessType = BusinessType.DELETE)
    @DeleteMapping("/removeCourse/{classId}/{courseId}")
    public AjaxResult removeClassCourse(@PathVariable("classId") Long classId, @PathVariable("courseId") Long courseId) {
        return toAjax(examClassService.removeClassCourse(classId, courseId));
    }

    @ApiOperation("查询当前用户参加的班级列表")
    @GetMapping("/myClasses")
    public TableDataInfo<ExamClassVo> getMyClasses(ExamClassVo entity) {
        return examClassService.queryUserClassList(entity);
    }
}
